﻿//-----------------------------------------------------------------------
// <copyright file="MLManageScripts.cs" company="MAPILab Ltd">
//     Copyright (c) MAPILab Ltd.  All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace MAPILab.SharePoint.Explorer.Managment
{
    using System;
    using System.Collections.Specialized;
    using System.ComponentModel;
    using System.Windows.Forms;
    using MAPILab.SharePoint.Explorer.CodeForm;
    using MAPILab.SharePoint.Explorer.Properties;
    using MAPILab.SharePoint.Explorer.Utilities;

    /// <summary>
    /// Form fo manage stored scripts
    /// </summary>
    public partial class MLManageScripts : Form
    {
        #region Fields

        /// <summary>
        /// Main form item
        /// </summary>
        private MLMainForm mainForm;

        /// <summary>
        /// selected script
        /// </summary>
        private string selectedScript = String.Empty;

        #endregion

        #region Properties

        /// <summary>
        /// Get and set mail form item
        /// </summary>
        public MLMainForm MainForm
        {
            get { return this.mainForm; }
            set { this.mainForm = value; }
        }

        #endregion

        #region Constructor

        /// <summary>
        /// Default form constructor
        /// </summary>
        public MLManageScripts()
        {
            Initialize();
        }

        /// <summary>
        /// Constructor with selected script
        /// </summary>
        /// <param name="selectedScript">selected script</param>
        public MLManageScripts(string selectedScript)
        {
            this.selectedScript = selectedScript;
            Initialize();
        }

        #endregion

        #region Methods

        /// <summary>
        /// Initialize form
        /// </summary>
        private void Initialize()
        {
            InitializeComponent();
            //Update Buttons
            UpdateButtons();

            //Load Stored and startupScripts
            InsertScripts(Settings.Default.startupScripts, true);
            InsertScripts(Settings.Default.storedScripts, false);
        }

        /// <summary>
        /// Insert script in scriptlist
        /// </summary>
        /// <param name="scriptPaths">Script paths</param>
        /// <param name="startup">Is startup</param>
        void InsertScripts(StringCollection scriptPaths, bool startup)
        {
            if (scriptPaths == null)
            {
                return;
            }

            foreach (string striptPath in scriptPaths)
            {
                ListViewItem lvi = scriptList.Items.Add(striptPath);

                if (startup)
                {
                    lvi.Checked = true;
                }

                if (selectedScript.Equals(striptPath, StringComparison.CurrentCultureIgnoreCase))
                {
                    lvi.Selected = true;
                }
            }
        }

        /// <summary>
        /// Save Script List
        /// </summary>
        void SaveList()
        {
            if (Settings.Default.startupScripts == null)
            {
                Settings.Default.startupScripts = new System.Collections.Specialized.StringCollection();
            }
            else
            {
                Settings.Default.startupScripts.Clear();
            }

            if (Settings.Default.storedScripts == null)
            {
                Settings.Default.storedScripts = new System.Collections.Specialized.StringCollection();
            }
            else
            {
                Settings.Default.storedScripts.Clear();
            }

            //save scripts
            foreach(ListViewItem item in scriptList.Items)
            {
                if (item.Checked)
                {
                    Settings.Default.startupScripts.Add(item.Text);
                }
                else
                {
                    Settings.Default.storedScripts.Add(item.Text);
                }
            }

            Settings.Default.Save();
        }

        /// <summary>
        /// Update buttons
        /// </summary>
        private void UpdateButtons()
        {
            int selCount = scriptList.SelectedItems.Count;
            edit.Enabled = (selCount == 1);
            remove.Enabled = (selCount > 0);
        }

        /// <summary>
        /// Open script for edit
        /// </summary>
        private void EditScript()
        {
            try
            {
                if (scriptList.SelectedItems.Count != 1)
                    return;

                //Load selected script to code form
                ListViewItem selectedItem = scriptList.SelectedItems[0];

                string path = selectedItem.Text;
                if (!path.Contains("\\"))
                {
                    //Script has been made automaticly
                    path = MLUtils.GetRoot() + path;
                }

                MLCodeForm codeForm = new MLCodeForm(path);

                codeForm.CodeLanguage = MLUtils.GetCodeLanguage(selectedItem.Text);

                codeForm.MainForm = mainForm;

                Close();

                //Choose form style
                if (mainForm.dockPanel.DocumentStyle == MAPILab.SharePoint.Explorer.Docking.DocumentStyle.SystemMdi)
                {
                    codeForm.MdiParent = mainForm;
                    codeForm.Show();
                }
                else
                {
                    codeForm.Show(mainForm.dockPanel);
                }
            }
            catch (Exception ex)
            {
                mainForm.CheckExceptionToDisplay(ex, scriptList.SelectedItems[0].Text);
            }
        }

        #endregion

        #region Events

        /// <summary>
        /// On add button click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void add_Click(object sender, EventArgs e)
        {
            if (Settings.Default.CodeLanguage == "VBNet")
                addScripts.FilterIndex = 2;
            else
                addScripts.FilterIndex = 1;

            if (addScripts.ShowDialog() != DialogResult.OK)
                return;

            foreach(string fileName in addScripts.FileNames)
            {
                bool duplicate = false;
                
                foreach(ListViewItem lvi in scriptList.Items)
                {
                    if (lvi.Text.ToLower() == fileName.ToLower())
                    {
                        duplicate = true;
                        break;
                    }
                }

                if (!duplicate)
                {
                    scriptList.Items.Add(fileName);
                }
            }

            SaveList();
        }

        /// <summary>
        /// On ScriptList Selected Index Changed
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void scriptList_SelectedIndexChanged(object sender, EventArgs e)
        {
            UpdateButtons();
        }

        /// <summary>
        /// On closing
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MangeScripts_FormClosing(object sender, FormClosingEventArgs e)
        {
            SaveList();
        }

        /// <summary>
        /// Edit button click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void edit_Click(object sender, EventArgs e)
        {
            EditScript();
        }

        /// <summary>
        /// On remove button click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void remove_Click(object sender, EventArgs e)
        {
            
            if(scriptList.SelectedItems.Count <= 0)
                return;

            for (int i=scriptList.Items.Count-1;i>=0;i--)
                if (scriptList.Items[i].Selected)
                {
                    scriptList.Items.RemoveAt(i);
                }

            SaveList();
        }

        /// <summary>
        /// On help button click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ManageScripts_HelpButtonClicked(object sender, CancelEventArgs e)
        {
            e.Cancel = true;
            MAPILab.SharePoint.Explorer.Information.MLHtmlHelper.ShowTopic(this, "explorer", 120);
        }

        /// <summary>
        /// On this form show
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ManageScripts_Shown(object sender, EventArgs e)
        {
            if (!Settings.Default.dontShowStoredScrTip)
            {
                MLManageScriptsTip tip = new MLManageScriptsTip();
                tip.ShowDialog();
            }
        }

        #endregion
    }
}
